package com.test.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLPropertiesConfiguration;

/**
 * 配置操作类. <br>
 * 读取配置文件.
 * <p>
 * Copyright: Copyright (c) Nov 16, 2010 12:54:56 PM
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * 
 * @author suncg@c-platform.com
 * @version 1.0.0
 */
public class ConfigUtils {

	private Configuration config = null;

	public ConfigUtils(String file, TYPE type) throws ConfigurationException {
		try {
			if ((TYPE.XML).equals(type)) {
				config = new XMLPropertiesConfiguration(file);
			} else if ((TYPE.PROPERTY).equals(type)) {
				config = new PropertiesConfiguration(file);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw new ConfigurationException();
		}
	}

	/**
	 * 添加配置文件信息.<br>
	 * 
	 * @param key
	 *            key值
	 * @param value
	 *            value值
	 */
	public void addProperty(String key, Object value) {
		config.addProperty(key, value);
	}

	/**
	 * 通过key值读取value值.<br>
	 * 
	 * @param key
	 *            key值
	 * @return
	 */
	public Object getValue(String key) {
		return config.getProperty(key);
	}

	/**
	 * 读取配置文件所有的是key-value值.<br>
	 * 
	 * @return
	 */
	public Map<String, Object> getAllValue() {
		Map<String, Object> configurationMap = new HashMap<String, Object>();
		Iterator<?> keys = config.getKeys();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			configurationMap.put(key, getValue(key));
		}
		return configurationMap;
	}

	/**
	 * 根据key值删除指定的property.<br>
	 * 
	 * @param key
	 *            key值
	 */
	public void remove(String key) {
		config.clearProperty(key);
	}

	/**
	 * 修改配置文件值.<br>
	 * 
	 * @param key
	 *            key值
	 * @param value
	 *            value值
	 */
	public void modify(String key, String value) {
		config.setProperty(key, value);
	}

	/**
	 * 删除所有值.<br>
	 */
	public void removeAll() {
		config.clear();
	}

	/**
	 * 判断是否包含key值.<br>
	 * 
	 * @param key
	 *            key值
	 * @return
	 */
	public boolean contains(String key) {
		return config.containsKey(key);
	}

	public static enum TYPE {
		XML("xml"), PROPERTY("property");

		private String type;

		private TYPE(String type) {
			this.type = type;
		}

		public String get() {
			return type;
		}

		@Override
		public String toString() {
			return type;
		}
	}

}
